var editObj=null,ptable=null,treeGrid=null,tableId='treeTable',layer=null;
layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var treeGrid = layui.treeGrid;//很重要

    //获取当前控制设备信息
    var _ticket = $.cookie("token");
    if(_ticket == null || _ticket == ""){
        layer.confirm('控制设备登录已过期，请中重新登录', {icon: 3, title: '提示信息'}, function (tips) {});
        window.location.href = "http://localhost:8083/login";
    }

    var option = {
        id:tableId
        ,elem: '#'+tableId
        ,url:'/ctrlequipment/type/list'
        ,cellMinWidth: 100
        ,idField:'id'//必須字段
        ,treeId:'id'//树形id字段名称
        ,treeUpId:'parentId'//树形父id字段名称
        ,treeShowName:'name'//以树形式显示的字段
        ,heightRemove:[".dHead",10]//不计算的高度,表格设定的是固定高度，此项不生效
        ,height:'full-100'
        ,isFilter:false
        ,iconOpen:true//是否显示图标【默认显示】
        ,isOpenDefault:true//节点默认是展开还是折叠【默认展开】
        ,loading:true
        ,method:'post'
        ,limit : 20
        ,isPage:false
        ,cols: [[
            {type:'numbers'}
            ,{type:'checkbox',sort:true}
            ,{field:'name', minWidth:250, title: '名称'}
            ,{field:'remarks', title: '类型编号'}
            ,{field: 'createDate', minWidth:120, title: '添加时间', sort: true,align:'center',templet:function(d){
                    //处理时间
                    var date = new Date(d.createDate);
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                }}
            ,{Width:100,title: '操作', align:'center',templet: function(d){
                    var html='';
                    var addBtn='<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>';
                    /*var config_statusBtn='<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="config_status">配置状态</a>';*/
                    // var config_Btn='<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="config_status">配置按钮</a>';
                    var delBtn='<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
                    return addBtn  + '' + delBtn;
                }
            }
        ]]
        ,parseData:function (res) {//数据加载后回调
            return res;
        }
        ,onClickRow:function (index, o) {
            /*console.log(index,o,"单击！");*/
        }
        ,onDblClickRow:function (index, o) {
            /*console.log(index,o,"双击");*/
        }
    };

    //控制设备列表
    ptable=treeGrid.render(option);

    treeGrid.on('tool('+tableId+')',function (obj) {
        if(obj.event === 'del'){//删除行
            del(obj);
        }else if(obj.event==="edit"){//添加行
            var index = layui.layer.open({
                title : "修改控制设备类型信息",
                type : 2,
                content : "ctrlEquipmentTypeEdit?id=" + obj.data.id,
                area: ['100%',$(document).height() + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回控制设备信息列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }
    });

    //查询
    $(".search_btn").on("click",function(){
        var searchKey = $(".searchVal").val();
        if(searchKey != ''){
            option.url = '/scene/query';
            option.where = {name: searchKey};
            treeGrid.render(option);
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = treeGrid.checkStatus(tableId),
            data = checkStatus.data,
            idArr = [];
        if(data.length > 0) {
            for (var i in data) {
                idArr.push(data[i].id);
            }
            layer.confirm('确定删除选中的控制设备记录？', {icon: 3, title: '提示信息'}, function (index) {
                for(var i=0;i<idArr.length;i++){
                    $.get("/ctrlequipment/type/delete?id=" + idArr[i],function(data){
                        if (data.code == 200) {
                            layer.msg("删除成功！");
                        } else {
                            layer.msg("删除失败，请重试！");
                        }
                        ptable.reload();
                        layer.close(index);
                    });
                }
            })
        }else{
            layer.msg("请选择需要删除的控制设备");
        }
    });

    //添加顶级控制设备数据
    $(".addBtn").click(function(){
        var index = layui.layer.open({
            title : "添加控制设备数据",
            type : 2,
            content : "ctrlEquipmentTypeAdd",
            area: ['100%',$(document).height() + 'px'],
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                setTimeout(function(){
                    layui.layer.tips('点击此处返回控制设备列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        });
    });

    function del(obj) {
        layer.confirm("你确定删除数据吗？如果存在下级节点则一并删除", {icon: 3, title:'提示'},
            function(index){//确定回调
                layer.close(index);
                $.get("/ctrlequipment/type/delete?id=" + obj.data.id,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    ptable.reload();
                    layer.close(index);
                });
            },function (index) {//取消回调
                layer.close(index);
            }
        );
    }


});